package com.sfang.common.base.token;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sfang.common.redis.Cache;
import com.sfang.common.redis.enums.OauthCacheType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Component
@Slf4j
public class TokenUtils {

    public JSONObject getJSONObjectByToken() {
        try {
            // 去redis查询
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String tokenPayload = request.getHeader("tokenPayload");

            if (StringUtils.isEmpty(tokenPayload)) {
                return null;
            }

            if (StringUtils.isNotEmpty(tokenPayload)) {
                JSONObject jsonObject = JSONObject.parseObject(tokenPayload);
                return JSON.parseObject(Cache.get(OauthCacheType.OAuthUserInfo,
                        jsonObject.get("clientId").toString()
                                + "|" + jsonObject.get("deviceType").toString()
                                + "|" + jsonObject.get("userId").toString()
                                + "|" + jsonObject.get("deviceNo").toString()));
            }

            return null;

        } catch (Exception e) {
            log.error("获取缓存用户信息失败 ", e);
            return null;
        }
    }

    public SaUserInfo getSaUserInfo() {
        try {
            // 去redis查询
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String tokenPayload = request.getHeader("tokenPayload");
            if (StringUtils.isEmpty(tokenPayload)) {
                return null;
            }
            if (StringUtils.isNotEmpty(tokenPayload)) {
                JSONObject jsonObject = JSONObject.parseObject(tokenPayload);
                if (Objects.equals(jsonObject.getString("clientId"), "sa-admin")) {
                    return null;
                }
                return JSON.parseObject(Cache.get(OauthCacheType.OAuthUserInfo,
                        jsonObject.getString("clientId")
                                + "|" + jsonObject.getString("deviceType")
                                + "|" + jsonObject.getString("userId")
                                + "|" + jsonObject.getString("deviceNo")), SaUserInfo.class);
            }
            return null;
        } catch (Exception e) {
            log.error("获取缓存用户信息失败 ", e);
            return null;
        }
    }
}
